package com.ct.lotterysystem.service.impl;

import com.ct.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.ct.lotterysystem.common.exception.ServiceException;
import com.ct.lotterysystem.common.utils.CaptchaUtil;
import com.ct.lotterysystem.common.utils.RedisUtil;
import com.ct.lotterysystem.common.utils.RegexUtil;
import com.ct.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    // 对于 redis 里面的 key需要标准化: 为了区分业务, 应该给 key 定义前缀:
    // VerificationCode_13111111111 : 1355,  User_1311111111 : userInfo

    private static final String VERIFICATION_CODE_PREDIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;
    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_318315410";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {

        // 校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        // 生成随机验证码
        String code = CaptchaUtil.getCaptcha(4);

        // 发送验证码
        // <"code":"xxx">
        // 这个发送不了, 可以不用写
//        Map<String, String> mao = new HashMap<>();
//        map.put("code", code);
//        smsUtil.ssendMessage(
//                VERIFICATION_CODE_TEMPLATE_CODE,
//                phoneNumber,
//                JacksonUtil.writerValueAsString(map);
//        );

        // 缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREDIX + phoneNumber, code, VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        // 校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        return redisUtil.get(VERIFICATION_CODE_PREDIX + phoneNumber);
    }
}
